<template>
  <div class="createPost-container">
    <h2 style="text-align: center;">发布新闻</h2>

    <!-- <el-steps :active="1"
              process-status="wait"
              align-center
              style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps> -->
    <el-form ref="postForm"
             :model="postForm"
             :rules="rules"
             class="form-container">

      <sticky :z-index="10"
              :class-name="'sub-navbar draft'+postForm.status">
        <!-- <CommentDropdown v-model="postForm.comment_disabled" />
        <PlatformDropdown v-model="postForm.platforms" />
        <SourceUrlDropdown v-model="postForm.source_uri" /> -->
        <div v-if="isupdate === false">
          <el-button v-loading="loading"
                     type="success"
                     class="publish_btn"
                     @click="submitForm">
            发布
          </el-button>
          <el-button v-loading="loading"
                     type="warning"
                     @click="draftForm">
            草案
          </el-button>
        </div>
        <div v-if="isupdate === true">
          <el-button v-loading="loading"
                     type="primary"
                     class="publish_btn"
                     @click="updateForm">
            修改
          </el-button>
        </div>

      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;"
                          prop="title">
              <MDinput v-model="postForm.title"
                       :maxlength="100"
                       name="name"
                       required>
                新闻标题

              </MDinput>
              <span v-show="contentShortLength"
                    class="word-counter">{{ contentShortLength }} word</span>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px"
                                label="作者:"
                                prop="writer"
                                class="postInfo-container-item">
                    <!-- <el-select v-model="postForm.writer"
                               :remote-method="getRemoteUserList"
                               filterable
                               default-first-option
                               remote
                               placeholder="请输入作者">
                      <el-option v-for="(item,index) in userListOptions"
                                 :key="item+index"
                                 :label="item"
                                 :value="item" />
                    </el-select> -->
                    <el-input v-model="postForm.writer"
                              placeholder="请输入作者" />
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="120px"
                                label="发布时间:"
                                prop="publish_time"
                                class="postInfo-container-item">
                    <el-date-picker v-model="postForm.publish_time"
                                    type="datetime"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    placeholder="请选择发布时间" />
                  </el-form-item>
                </el-col>

                <!-- <el-col :span="6">
                  <el-form-item label-width="90px"
                                label="重要性:"
                                class="postInfo-container-item">
                    <el-rate v-model="postForm.importance"
                             :max="3"
                             :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                             :low-threshold="1"
                             :high-threshold="3"
                             style="display:inline-block" />
                  </el-form-item>
                </el-col> -->
              </el-row>
            </div>
          </el-col>
        </el-row>

        <!-- <el-form-item style="margin-bottom: 40px;"
                      label-width="70px"
                      label="摘要:">
          <el-input v-model="postForm.content_short"
                    :rows="1"
                    type="textarea"
                    class="article-textarea"
                    autosize
                    placeholder="请输入摘要内容" />
          <span v-show="contentShortLength"
                class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item> -->

        <el-form-item prop="content"
                      style="margin-bottom: 30px;">
          <Tinymce ref="editor"
                   v-model="postForm.content"
                   :height="400" />
        </el-form-item>

        <el-form-item prop="image"
                      style="margin-bottom: 30px;">
          <Upload v-model="postForm.image" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'// 富文本
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import newsApi from '@/api/news'
import Warning from './Warning'
import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './Dropdown'

// const defaultForm = {
//   status: 'draft',
//   title: '', // 文章题目
//   writer: '',
//   publish_time: '',
//   // this.utils.getNowTime()
//   content: '', // 文章内容
//   content_short: '', // 文章摘要
//   source_uri: '', // 文章外链
//   image: '', // 文章图片
//   display_time: undefined, // 前台展示时间
//   id: undefined,
//   platforms: ['a-platform'],
//   comment_disabled: false,
//   importance: 0
// }

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Upload, Sticky, Warning, CommentDropdown, PlatformDropdown, SourceUrlDropdown },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      postForm: {
        status: 'draft',
        // title: this.$store.getters.newinfo.title, // 文章题目
        // writer: this.$store.getters.newinfo.writer,
        // publish_time: this.$store.getters.newinfo.publish_time,
        title: '', // 文章题目
        writer: '',
        publish_time: '',
        content: '', // 文章内容
        content_short: '', // 文章摘要
        source_uri: '', // 文章外链
        image: '', // 文章图片
        display_time: undefined, // 前台展示时间
        id: undefined,
        platforms: ['a-platform'],
        comment_disabled: false,
        importance: 0
      },
      // loading: false,
      userListOptions: [],
      rules: {
        image: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        writer: [{ validator: validateRequire }],
        publish_time: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
        // source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {},
      isupdate: false
    }
  },
  computed: {
    contentShortLength () {
      return this.postForm.title.length
    }
    // displayTime: {
    //   // set and get is useful when the data
    //   // returned by the back end api is different from the front end
    //   // back end return => "2013-06-25 06:59:25"
    //   // front end need timestamp => 1372114765000
    //   get () {
    //     return (+new Date(this.postForm.display_time))
    //   },
    //   set (val) {
    //     this.postForm.display_time = new Date(val)
    //   }
    // }
  },
  created () {
    if (this.$route.params && this.$route.params.id) {
      // 从路径获取id值
      const id = this.$route.params.id
      if (id === ':id') {
        console.log('无参数')
      } else {
        // 调用根据id查询的方法
        this.isupdate = true
        this.fetchData(id)
      }
    }
    //  else { // 路径没有id值，做添加
    //   // 清空表单
    //   this.postForm = {}
    // }
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    // this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData (id) {
      newsApi.getNewsInfoById(id)
        .then(response => { // 请求成功
          console.log(response)
          this.postForm.title = response.data[0].title
          this.postForm.writer = response.data[0].writer
          this.postForm.content = response.data[0].content1
          this.postForm.image = response.data[0].content1_img
          this.postForm.publish_time = response.data[0].publish_time
          this.postForm.id = response.data[0].news_id
          console.log('后去该新闻', this.postForm)
        })
      // newsApi(id).then(response => {
      //   this.postForm = response.data

      //   // just for test
      //   this.postForm.title += `   Article Id:${this.postForm.id}`
      //   this.postForm.content_short += `   Article Id:${this.postForm.id}`

      //   // set tagsview title
      //   this.setTagsViewTitle()

      //   // set page title
      //   this.setPageTitle()
      // }).catch(err => {
      //   console.log(err)
      // })
    },
    // setTagsViewTitle () {
    //   const title = 'Edit Article'
    //   const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
    //   this.$store.dispatch('tagsView/updateVisitedView', route)
    // },
    // setPageTitle () {
    //   const title = 'Edit Article'
    //   document.title = `${title} - ${this.postForm.id}`
    // },
    submitForm () {
      console.log('源生成：', this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          const obj = {
            title: this.postForm.title, // 文章题目
            writer: this.postForm.writer,
            publish_time: this.utils.getdate(this.utils.gettime(this.postForm.publish_time)),
            // publish_time: this.postForm.publish_time,
            content: this.postForm.content // 文章内容
            // update_time: this.utils.getNowTime()
          }
          console.log('提交发布：', obj)
          newsApi.addNewsInfo(obj)
            .then(response => { // 请求成功
              console.log(response)
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              })
              this.postForm.status = 'published'
              this.loading = false
              // 跳转列表
              this.$router.push({ path: '/news/index' })
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm () {
      if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      const newinfo = {
        content: this.postForm.content,
        title: this.postForm.title,
        writer: this.postForm.writer,
        publish_time: this.utils.getdate(this.utils.gettime(this.postForm.publish_time))

        // publish_time: this.postForm.publish_time
      }
      // console.log('缓存', newinfo)
      this.$store.dispatch('user/getnewInfo', newinfo)
      this.$message({
        message: `保存成功`,
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    },
    // 修改
    updateForm () {
      const obj = {
        title: this.postForm.title, // 文章题目
        writer: this.postForm.writer,
        // publish_time: this.utils.gettime(this.postForm.publish_time),
        publish_time: this.utils.getdate(this.utils.gettime(this.postForm.publish_time)),

        // publish_time: this.postForm.publish_time,
        content: this.postForm.content, // 文章内容
        update_time: this.utils.getNowTime(),
        news_id: this.postForm.id
      }
      console.log('修改：', obj)
      newsApi.updateNewsInfo(obj)
        .then(response => {
          this.$message({
            type: 'success',
            message: `新闻：${this.postForm.id},修改成功!`
          })
          this.$router.push({ path: '/news/index' })
        })
    }
    // getRemoteUserList (query) {
    //   searchUser(query).then(response => {
    //     if (!response.data.items) return
    //     this.userListOptions = response.data.items.map(v => v.name)
    //   })
    // }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 50px;
    position: absolute;
    right: 20px;
    top: 30px;
    color: #bfcbd9;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

// 发布按钮
.publish_btn {
  margin-left: 50px;
}
</style>
